package com.hqbzl.chat.service.impl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.hqbzl.chat.service.Session;

import io.netty.channel.Channel;

public class SessionMemoryImpl implements Session {
	private final ConcurrentHashMap<String, Channel> userChannelMap = new ConcurrentHashMap<>();
	private final ConcurrentHashMap<Channel, String> channelUserMap = new ConcurrentHashMap<>();
	private final ConcurrentHashMap<Channel, Map<String, Object>> channelAttrMap = new ConcurrentHashMap<>();

	@Override
	public void bind(Channel channel, String userName) {
		userChannelMap.put(userName, channel);
		channelUserMap.put(channel, userName);
		channelAttrMap.put(channel, new ConcurrentHashMap<>());
	}

	@Override
	public void unbind(Channel channel) {
		final String userName = channelUserMap.remove(channel);
		userChannelMap.remove(userName);
		channelAttrMap.remove(channel);
	}

	@Override
	public Object getAttr(Channel channel, String name) {
		return channelAttrMap.get(channel).get(name);
	}

	@Override
	public void setAtt(Channel channel, String key, Object value) {
		final Map<String, Object> attr = channelAttrMap.get(channel);
		attr.put(key, value);
	}

	@Override
	public Channel getChannel(String userName) {
		return userChannelMap.get(userName);
	}
}
